include ActionController
class EventsController < ApplicationController
  before_filter :validate_state, :only => [:index, :choose_for_state_change]
  before_filter :manager_required, :except => [:show, :index, :attend, :unattend, :update_availability]
  before_filter :login_required
  before_filter :load_event_counts, :only => [:index]
  
  @@cols = Event.column_names

  resources_controller_for :events
  
  include ApplicationHelper
  
  def act
    resources = resource_service.find(:all, :conditions => ['id in (?)', params[:events]])
    if resources.empty?
      begin
        return redirect_to(:back)
      rescue RedirectBackError
        return redirect_to(resources_url)
      end
    end
    if params[:state] == 'cfw' and resources[0].state == 'new' and params[:confirm] != 'true'
      return redirect_to(new_admin_call_for_worker_url(:events => resources))
    end
    resources.each do |resource|
      resource.switch(params[:state])
      resource.save
    end
    redirect_to resources_url(:state => params[:state])
  end
  
  def update_availability
    if params[:return_event]
      redirect_to resource_url(params[:return_event])
    else
      redirect_to resources_url(:state => params[:state]) 
    end
    return if params[:attendances].nil?
    Event.transaction do
      params[:attendances].each do |k, v|
        event = resource_service.find(k)
        if event.state == 'cfw'
          if ['1', '2', '3'].member? v
            current_user.attend event, v.to_i
            event.save
          elsif v == '0' and current_user.can_attend? event
            current_user.unattend event
            event.save
          end
        end
      end
    end
    flash[:notice] = :availability_updated.l
  end
  
  def assign
    @resource = resource_service.find(params[:id])
    user = User.find(params[:user_id])
    user.assign_to(@resource)
    redirect_to resource_url(@resource)
  end
  
  def deassign
    @resource = resource_service.find(params[:id])
    user = User.find(params[:user_id])
    user.deassign_from(@resource)
    redirect_to resource_url(@resource)
  end
  
  def choose_for_state_change
    @events = find_resources
    self.resources = find_resources
  end
  
  private
  def find_resources
    @sort = params[:sort]
    if @sort.nil?
      @sort = session[:event_sort] || 'start_date'
    else
      session[:event_sort] = @sort
      session[:reverse_events] = !session[:reverse_events]
    end
    sorting_by_simple_column = @@cols.member? @sort
    @state = params[:state] || Event.all_states(current_user).first
    params = {:conditions => ['state=?', @state]}
    params[:order] = "#{@sort} asc" if sorting_by_simple_column
    events = resource_service.find(:all, params).reject{|event|!event.should_show_to? current_user}
    s=@sort.to_sym
    events = events.sort_by{|i|i.respond_to?(s) ? i.send(s) : i.id} unless sorting_by_simple_column
    return events
  end
  
  def validate_state
    redirect_to :action => 'index' unless params[:state].nil? || Event.all_states(current_user).member?(params[:state])
  end
  
  def load_event_counts
    @event_counts = {}
    events = []
    if logged_in_as_manager?
      events = Event.find_by_sql("select state, count(*) as count from events group by state")
    else
      events.push(*Event.find_by_sql("select state, count(*) as count from events where state='cfw' group by state"))
      events.push(*Event.find_by_sql("select e.state, count(*) as count from attendances a, events e where a.event_id=e.id and a.user_id=#{current_user.id} group by e.state"))
    end
    events.each do |e|
      @event_counts[e.state] = e.count
    end
  end
  
end